package listStudy;

import common.utils.ListNode;

import java.util.ArrayList;

public class ListStudy02 {

    /**
     * 题目二：从尾到头打印链表
     * @param args
     */
    public static void main(String[] args) {
        //创建一个单链表
        ListNode head = new ListNode(1);
        ListNode pre = head;
        for (int i = 2; i <= 10; i++){
            pre.next = new ListNode(i);
            pre=pre.next;
        }
        ArrayList<Integer> integers = printListFromTailToHead(head);
        for (Integer integer : integers) {
            System.out.println(integer);
        }
    }

    public static ArrayList<Integer> printListFromTailToHead(ListNode head){
        ArrayList<Integer> results = new ArrayList<>();
        reverseList(head, results);
        return results;
    }

    /**
     * 递归， 树的后序遍历
     * @param head
     * @param results
     */
    public static void reverseList(ListNode head, ArrayList<Integer> results){
        //出口
        if (head == null) return;
        //递归调用，需要越来越靠近出口
        reverseList(head.next, results);
        //递归体，递归调用后处理结果，相当于树的后序遍历
        results.add(head.val);
    }
}
